<script setup>
import {onMounted, ref} from 'vue'

defineProps({
  msg: String,
})

const audioContainerRef = ref()
const audioEleRef = ref()

onMounted(() => {
  console.log(audioContainerRef.value)
  console.log(audioEleRef.value)

  const mimeTypes = [
    // 视频格式
    'video/webm',
    'video/webm;codecs=vp8',
    'video/webm;codecs=vp9',
    'video/webm;codecs=vp8,opus',
    'video/webm;codecs=vp9,opus',
    'video/webm;codecs=daala',
    'video/webm;codecs=h264',
    'video/webm;codecs=vp8,pcm',
    'video/webm; codecs="av01"',
    'video/mp4',
    'video/mp4;codecs="avc1.42E01E"',
    'video/mp4;codecs=avc1.640028,mp4a.40.2',
    'video/mp4;codecs=avc1.640028,opus',
    'video/mp4;codecs=hvc1.1.6.L186.B0,mp4a.40.2',
    'video/mp4;codecs=hvc1.1.6.L186.B0,opus',
    'video/mp4;codecs="av01.0.05M.08"',
    'video/mp4;codecs=av01.0.19M.08,mp4a.40.2',
    'video/mp4;codecs=av01.0.19M.08,opus',
    'video/mp4;codecs="hev1.1.6.L93.B0"',
    'video/ogg',
    'video/quicktime',
    'video/3gpp',
    'video/3gp2',
    'application/mp4',
    'video/x-msvideo',
    'video/x-matroska',
    'video/x-flv',
    'application/vnd.apple.mpegurl',

    // 音频格式
    'audio/mpeg',
    'audio/webm',
    'audio/webm;codecs=vorbis',
    'audio/webm;codecs=opus',
    'audio/webm;codecs=pcm',
    'audio/ogg;codecs=vorbis',
    'audio/3gpp',
    'audio/3gp2',
    'audio/mp4',
    'audio/aac',
    'audio/flac',
    'audio/wav',
    'audio/x-wav',
    'audio/x-m4a',
    'audio/x-ogg',
    'audio/x-scpls',
    'audio/x-mpegurl',
    'audio/flac',
    'audio/aac',
    'audio/pcm'
  ];

  for (const type of mimeTypes) {
    console.log(
        `支持 ${type} 类型吗？${
            MediaRecorder.isTypeSupported(type) ? "也许！" : "不能 :("
        }`,
    );
  }
})

function startAudio(){
  navigator.mediaDevices.getUserMedia({
    audio: true,
  }).then(stream => {
    console.log(stream, audioEleRef);
    audioEleRef.value.srcObject = stream;

    audioEleRef.value.addEventListener('loadedmetadata', () => {
      console.log('音频总时长:', audioEleRef.value.duration);
    });

    const options = {
      audioBitsPerSecond : 128000,
      videoBitsPerSecond : 2500000,
      mimeType : 'audio/webm'
    }
    const mediaRecorder = new MediaRecorder(stream, options);
    let chunks = [];

    mediaRecorder.onstop = (e) => {
      console.log("数据将在调用 MediaRecorder.stop() 后可用。");
      const clipName = prompt("输入音频片段的名称");

      const clipContainer = document.createElement("article");
      const clipLabel = document.createElement("p");
      const audio = document.createElement("audio");
      const deleteButton = document.createElement("button");
      const mainContainer = document.querySelector("body");

      clipContainer.classList.add("clip");
      audio.setAttribute("controls", "");
      deleteButton.textContent = "Delete";
      clipLabel.textContent = clipName;

      clipContainer.appendChild(audio);
      clipContainer.appendChild(clipLabel);
      clipContainer.appendChild(deleteButton);
      mainContainer.appendChild(clipContainer);

      audio.controls = true;
      const blob = new Blob(chunks, { type: "audio/webm" });
      chunks = [];
      audio.src = URL.createObjectURL(blob);
      console.log("录制停止");

      deleteButton.onclick = (e) => {
        const evtTgt = e.target;
        evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
      };
    };

    mediaRecorder.ondataavailable = (e) => {
      chunks.push(e.data);
    };

    audioEleRef.value.addEventListener('play', () => {
      console.log('开始播放');
      mediaRecorder.start();
      console.log(mediaRecorder.state);
      console.log("录制开始");
    });

    audioEleRef.value.addEventListener('pause', () => {
      console.log('暂停播放');
      mediaRecorder.stop();
      console.log(mediaRecorder.state);
      console.log("录制停止");
    });

    audioEleRef.value.addEventListener('ended', () => {
      console.log('播放完成');
    });

    audioEleRef.value.addEventListener('error', () => {
      console.error('播放出错:', audioEleRef.value.error);
    });
  }).catch((err) => {
    console.error(`发生以下错误：${err}`);
  });
}

const count = ref(0)
</script>

<template>
  <div class="container">
    <button @click="startAudio">开始录音</button>
    <div class="audio" ref="audioContainerRef">
      <audio id="audio" ref="audioEleRef" controls></audio>
    </div>
  </div>
</template>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
}

.audio {
  width: 500px;
  height: 100px;
}
</style>
